//删除节点
function nodedelete(id) {
    console.log(id);
    console.log(graph);
    var linkTemp = graph.links,
        nodeTemp = graph.nodes;

    //删除节点自身及相关连线数组
    for (var i = 0; i < linkTemp.length; i++) {
        if (linkTemp[i]["source"].index == id || linkTemp[i]["target"].index == id) {
            linkTemp.splice(i, 1);
            i--;
        }
    }

    for (var i = 0; i < nodeTemp.length; i++) {
        if (nodeTemp[i].index == id) {
            nodeTemp.splice(i, 1);
            i--;
        }
    }

    for (var i = 0; i < nodeTemp.length; i++) {
        nodeTemp[i].index = i;
    }

    for (var i = 0; i < linkTemp.length; i++) {
        linkTemp[i].index = i;
    }

    console.log(nodeTemp);
    console.log(linkTemp);

    graph["nodes"] = nodeTemp;
    graph["links"] = linkTemp;

    $('#container2 svg').html('');
    createForce(graph, userMenuData);

    //更新d3数据
    /*nodes = nodes.data(nodeTemp);
    nodes.exit().remove();
    links = links.data(linkTemp);
    links.exit().remove();*/

    /*$.each($('g.g-item'),function(i){
    	var vl=$(this).attr('vl');
    	if(vl==id){
    		$(this).remove();
    	}
    });
    $.each($('g.g-item'),function(i){
    	$(this).attr('vl',i);
    });*/

    /*$.each($('text.nodetext'),function(i){
    	if(i==id){
    		$(this).remove();	
    		$('defs.imgdefs').eq(i).remove();
    	}
    });
	
    $.each($('defs.imgdefs'),function(i){
    	$(this).find('pattern').attr('id','catpattern'+i);
    });*/

    force.restart();

}

//是否选中创建关系
function isChecked() {
    var chked = false;
    if ($('.relationship').hasClass('ischked')) {
        chked = true;
    } else {
        chked = false;
    }
    return chked;
}
$('.relationship').on('click', function() {
    if (!$(this).hasClass('ischked')) {
        $(this).addClass('ischked');
    } else {
        $(this).removeClass('ischked');
    }
});

//创建关系
function createRelation(d) {

    var primaryId = $('input[name=primaryId]').val(),
        primaryRowkey = $('input[name=primaryRowkey]').val(),
        primaryvl = $('input[name=primaryvl]').val(),
        secondaryId = $('input[name=secondaryId]').val(),
        secondaryRowkey = $('input[name=secondaryRowkey]').val(),
        secondaryvl = $('input[name=secondaryvl]').val();

    var suc = false;

    var strCont = '';
    $.ajax({
        type: "get",
        url: unifiedUserUrl + 'object/' + primaryId + '/link',
        async: true,
        xhrFields: { withCredentials: true },
        success: function(data) {

            strCont += '<div class="relationBox"><ul>';
            strCont += '<li><label>选择关系：</label><select id="selRelation">';
            for (var i = 0; i < data.length; i++) {
                strCont += '<option data-linkuri="' + data[i]["uri"] + '">' + data[i]['displayName'] + '</option>';
            }
            strCont += '</select></li><li><label>&nbsp;</label>';
            strCont += '<input type="button" class="btn relationBtn" value="创建关系" /></li>';
            strCont += '</ul></div>';

            layer.open({
                type: 1,
                title: '创建关系',
                area: ['340px', '200px'], //宽高
                content: strCont,
                cancel: function(index, layero) {
                    $('input[name=secondaryId]').val('');
                    $('input[name=secondaryRowkey]').val('');
                }
            });

            $('.relationBtn').on('click', function() {

                var linkuri = $('#selRelation option:selected').attr('data-linkuri');
                console.log(linkuri);
                $.ajax({
                    type: "POST",
                    url: unifiedUserUrl + 'relationgraph/analysis/relation',
                    data: { 'activeObjectUri': primaryId, 'activeRowKey': primaryRowkey, 'passiveObjectUri': secondaryId, 'passiveRowKey': secondaryRowkey, 'linkUri': linkuri },
                    async: true,
                    xhrFields: { withCredentials: true },
                    success: function(data, textStatus) {

                        console.log('创建关系：' + data["created"]);

                        if (textStatus == 'success') {

                            var len = graph['links'].length;
                            graph['links'][len] = { "source": primaryvl, "target": secondaryvl, "relation": "测试", "timeInterval": data["timeInterval"], "value": 1, "index": len }

                            $('#container2 svg').html('');
                            createForce(graph, userMenuData);
                            console.log(graph);

                            var tips = '成功创建关系';
                            if (data["created"] == false) {
                                tips = '边已存在';
                            }

                            layer.msg(tips, {
                                time: 2000
                            }, function() {
                                $('.relationship').removeClass('ischked');
                                $('input[name=primaryId]').val('');
                                $('input[name=primaryRowkey]').val('');
                                $('input[name=primaryvl]').val('');
                                $('input[name=secondaryId]').val('');
                                $('input[name=secondaryRowkey]').val('');
                                $('input[name=secondaryvl]').val('');
                                layer.closeAll();
                            });
                        }
                    }
                });
            });
        }
    });

}



//获取快照
getSnapshot();

function getSnapshot() {
    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'relationgraph/snapshot',
        async: true,
        xhrFields: { withCredentials: true },
        success: function(data) {
            var snapHtml = '';
            for (var i = 0; i < data.length; i++) {
                snapHtml += '<dl data-id="' + data[i]["id"] + '"><img class="imgAuto" src="' + data[i]["snapshot"] + '" alt="" /><h6>' + formatDate(data[i]["timeCreated"]) + '</h6></dl>';
            }
            $('#historyImg').html(snapHtml);

            //根据快照ID获取快照数据
            $('#historyImg dl').on('click', function() {
                var snapid = $(this).attr('data-id');
                $.ajax({
                    type: 'get',
                    url: unifiedUserUrl + 'relationgraph/snapshot/' + snapid,
                    xhrFields: { withCredentials: true },
                    success: function(result) {
                        console.log(result.data);
                        graph = JSON.parse(result.data);
                        //graph=graphFormat(graph);
                        $('#container2 svg').html('');
                        createForce(graph, userMenuData);

                    }
                });
            });

        }
    });
}

//点击生成快照
$('.snapshot').on('click', function() {

    var myDate = new Date();
    var canvas = $('#container2 svg')[0];
    //saveSvgAsPng(canvas, 'test-0519.png')
    svgAsPngUri(canvas, {}, function(uri) {
        //if(!$('.snapshot').hasClass('isFd')){
        graph = graphFormat(graph);
        //}
        $.ajax({
            type: 'post',
            url: unifiedUserUrl + 'relationgraph/snapshot',
            data: { 'snapshot': uri, 'data': JSON.stringify(graph) },
            xhrFields: { withCredentials: true },
            success: function(data, textStatus) {
                getSnapshot();
                $('.snapshot').addClass('isFd');
                if (textStatus == 'success') {
                    layer.msg('成功创建快照', {
                        time: 2000
                    }, function() {

                    });
                }

            }
        });

    });

});


//保存关联图数据
$('.saveGraph').on('click', function() {
    console.log(graph);
    graph = graphFormat(graph);
    $.ajax({
        type: 'POST',
        url: unifiedUserUrl + '/relationgraph',
        data: { 'data': JSON.stringify(graph) },
        async: true,
        xhrFields: { withCredentials: true },
        success: function(data, textStatus) {
            if (textStatus == 'success') {
                layer.msg('成功保存关联图', {
                    time: 2000
                }, function() {});
            }
        }
    });
});

//实例关联事件
function relationEvents(uri, rowkey) {
    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'object/' + uri + '/instance/' + rowkey + '/event',
        async: true,
        xhrFields: { withCredentials: true },
        success: function(data) {
            relationHandle(data);
        }
    });
}

//实例关联实体
function relationEntity(uri, rowkey) {
    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'object/' + uri + '/instance/' + rowkey + '/entity',
        async: true,
        xhrFields: { withCredentials: true },
        success: function(data) {
            relationHandle(data);
        }
    });
}

//实例关联文件
function relationDoc(uri, rowkey) {
    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'object/' + uri + '/instance/' + rowkey + '/doc',
        data: { 'objectUri': uri, 'instanceId': rowkey },
        async: true,
        xhrFields: { withCredentials: true },
        success: function(data) {
            relationHandle(data);
        }
    });
}

//实例关联多媒体
function relationMedia(uri, rowkey) {
    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'object/' + uri + '/instance/' + rowkey + '/media',
        data: { 'objectUri': uri, 'instanceId': rowkey },
        async: true,
        xhrFields: { withCredentials: true },
        success: function(data) {
            relationHandle(data);
        }
    });
}

//实例关联操作
function relationHandle(data) {

    graph = graphFormat(graph);

    var tempx1 = posx < 175 ? 25 : (posx - 150),
        tempx2 = posx > 955 ? 955 : (posx + 150),
        tempy1 = posy < 175 ? 25 : (posy - 150),
        tempy2 = posy > 955 ? 925 : (posy);

    var nodeslen = graph["nodes"].length,
        linkslen = graph["links"].length;

    for (var i = 0; i < data.length; i++) {

        var tempx = getRandom(tempx1, tempx2),
            tempy = getRandom(tempy1, tempy2);

        graph["nodes"][nodeslen] = { "index": nodeslen, "name": data[i]["displayName"], "image": data[i]["objectInfo"]["icon"], "x": tempx, "y": tempy, "uri": data[i]["objectUri"], "rowkey": data[i]["rowKey"], "parent": id, "isdel": true, "linkUri": data[i]["linkUri"], "objectType": data[i]["objectType"] };
        graph["links"][linkslen] = { "source": id, "target": nodeslen, "relation": data[i]["linkUri"], "value": 1, "timeInterval": data[i]["timeInterval"] };

        nodeslen++;
        linkslen++;
    }
    console.log(graph);
    $('#container2 svg').html('');
    createForce(graph, userMenuData);
}

//删除关联事件、关联实体、关联文件、关联多媒体
function relationDel(tp) {
    var nodesArr = graph["nodes"],
        linkArr = graph["links"];
    var tempArr = [];
    for (var i = 0; i < nodesArr.length; i++) {
        if (nodesArr[i]["parent"] == id && nodesArr[i]["isdel"] && nodesArr[i]["objectType"] == tp) {
            tempArr.push(nodesArr[i].index);
            nodesArr.splice(i, 1);
            i--;
        }
    }
    console.log(tempArr);

    for (var i = 0; i < linkArr.length; i++) {
        for (var j = 0; j < tempArr.length; j++) {
            if (linkArr[i]["source"].index == id && linkArr[i]["target"].index == tempArr[j]) {
                linkArr.splice(i, 1);
                i--;
            }
        }
    }

    for (var i = 0; i < nodesArr.length; i++) {
        nodesArr[i].index = i;
    }
    for (var i = 0; i < linkArr.length; i++) {
        linkArr[i].index = i;
    }

    graph["nodes"] = nodesArr;
    graph["links"] = linkArr;

    $('#container2 svg').html('');
    createForce(graph, userMenuData);
}

//获取关联线最小值及最大值
function getTimes() {
    var linkarr = graph['links'],
        minarr = [],
        maxarr = [],
        minT = 0,
        maxT = 0;
    if (linkarr.length > 0) {
        for (var i = 0; i < linkarr.length; i++) {
            minarr.push(linkarr[i]['timeInterval']['startTime']);
            maxarr.push(linkarr[i]['timeInterval']['endTime']);
        }
    }
    minT = Math.min.apply(null, minarr);
    maxT = Math.max.apply(null, maxarr);
    console.log(minT + ',' + maxT);

}

//是否选中创建关系
function isbeeline() {
    var chked = false;
    if ($('.beeline').hasClass('ischked')) {
        chked = true;
    } else {
        chked = false;
    }
    return chked;
}
$('.beeline').on('click', function() {
    if (!$(this).hasClass('ischked')) {
        $(this).addClass('ischked');
    } else {
        $(this).removeClass('ischked');
    }
});

//最短路径
function shortestPath() {

    var primaryId = $('input[name=primaryId]').val(),
        primaryRowkey = $('input[name=primaryRowkey]').val(),
        primaryvl = $('input[name=primaryvl]').val(),
        secondaryId = $('input[name=secondaryId]').val(),
        secondaryRowkey = $('input[name=secondaryRowkey]').val(),
        secondaryvl = $('input[name=secondaryvl]').val();

    var strCont = '';
    var aa = '{"objectUri":"' + primaryId + '","rowKey":"' + primaryRowkey + '"}';
    var bb = '{"objectUri":"' + secondaryId + '","rowKey":"' + secondaryRowkey + '"}';
    console.log(aa);
    $.ajax({
        type: 'get',
        url: unifiedUserUrl + 'object/instance/shortestpath',
        data: { "source": aa, "target": bb },
        xhrFields: { withCredentials: true },
        success: function(data) {

            console.log(data);



            strCont += '<div class="feelineBox"><ul>';
            for (var i = 0; i < data.length; i++) {
                var temprk = '';
                for (var j = 0; j < data[i].length; j++) {
                    temprk += data[i][j]["rowKey"] + ',';
                }
                if (temprk.length > 0) {
                    temprk = temprk.substring(0, temprk.length - 1);
                }
                strCont += '<li><input type="radio" id="line-' + i + '" name="lines" value="' + i + '" /><label class="route" data-route="' + temprk + '" for="line-' + i + '">路径' + (i + 1) + '</label></li>';
            }
            strCont += '</ul></div>';


            layer.open({
                type: 1,
                title: '最短路径',
                area: ['340px', '200px'], //宽高
                content: strCont,
                cancel: function(index, layero) {
                    $('input[name=secondaryId]').val('');
                    $('input[name=secondaryRowkey]').val('');
                    console.log('yyy:' + graph["nodes"]);
                    $('.beeline').removeClass('ischked');
                    $('#container2 svg').html('');
                    createForce(graph, userMenuData);
                }
            });


            $('label.route').on('click', function() {

                graph = graphFormat(graph);

                feelineLinks = graph["links"].concat();
                feelineNodes = graph["nodes"].concat();

                var rk = $(this).attr('data-route').split(",");
                var vl = $(this).siblings('input').val();
                var feenodelen = feelineNodes.length;

                var tempidxarr = [],
                    hidenodearr = [];

                console.log('fff:' + rk.length);
                for (var i = 0; i < rk.length; i++) {
                    var tempnum = 0;
                    for (var j = 0; j < feelineNodes.length; j++) {
                        if (rk[i] == feelineNodes[j]["rowkey"]) {
                            console.log(feelineNodes[j]);
                            tempidxarr.push(feelineNodes[j].index);
                            tempnum++;
                        }
                    }
                    if (tempnum == 0) {
                        var dtemp = data[vl][i];
                        var tempx = getRandom(25, 1000),
                            tempy = getRandom(25, 400);
                        feelineNodes[feenodelen] = { "index": feenodelen, "name": dtemp["displayName"], "image": dtemp["objectInfo"], "x": tempx, "y": tempy, "uri": dtemp["objectUri"], "rowkey": dtemp["rowKey"], "linkUri": dtemp["linkUri"], "objectType": dtemp["objectType"] };
                        tempidxarr.push(feenodelen);
                        feenodelen++;

                    }
                }

                var feelinklen = feelineLinks.length;
                console.log(tempidxarr.length);
                for (var i = 0; i < tempidxarr.length; i++) {
                    if (i < tempidxarr.length - 1) {
                        feelineLinks[feelinklen] = { "source": tempidxarr[i], "target": tempidxarr[i + 1], "relation": "", "value": 1, "color": "#F00", "timeInterval": "" };
                    }
                    feelinklen++;
                }

                var aa = { "nodes": [], "links": [] };
                aa["nodes"] = feelineNodes;
                aa["links"] = feelineLinks;

                $('#container2 svg').html('');
                createForce(aa, userMenuData);

            });




        }
    });
}

//时间轴
var Months = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];

function createDemos() {

    var linkarr = graph['links'],
        minarr = [],
        maxarr = [],
        minT = 0,
        maxT = 0;
    if (linkarr.length > 0) {
        for (var i = 0; i < linkarr.length; i++) {
            minarr.push(linkarr[i]['timeInterval']['startTime']);
            maxarr.push(linkarr[i]['timeInterval']['endTime']);
        }

        minT = Math.min.apply(null, minarr);
        maxT = Math.max.apply(null, maxarr);

        var date = $("<div id='date' />").appendTo($("#dateSlider")); //渲染日期组件
        var dateSilderObj = date.dateRangeSlider({
            arrows: true, //是否显示左右箭头
            bounds: { min: new Date(minT), max: new Date(maxT) }, //最大 最少日期
            defaultValues: { min: new Date(minT), max: new Date(maxT) } //默认选中区域
            ,
            scales: [{
                first: function(value) { return value; },
                end: function(value) { return value; },
                next: function(val) {
                    var next = new Date(val);
                    return new Date(next.setMonth(next.getMonth() + 1));
                },
                label: function(val) {
                    return Months[val.getMonth()];
                },
                format: function(tickContainer, tickStart, tickEnd) {
                    tickContainer.addClass("myCustomClass");
                }
            }]
        }); //日期控件
        //重新赋值（整个时间轴）
        dateSilderObj.dateRangeSlider("bounds", new Date(minT), new Date(maxT));

        //重新赋值（选中区域）
        dateSilderObj.dateRangeSlider("values", new Date(minT), new Date(maxT));
        console.log(new Date(minT));

        //拖动完毕后的事件
        dateSilderObj.bind("valuesChanged", function(e, data) {
            var val = data.values;
            var stime = formatDate(val.min);
            var etime = formatDate(val.max);

            for (var i = 0; i < linkarr.length; i++) {
                if (linkarr[i]['timeInterval']['startTime'] >= val.min && linkarr[i]['timeInterval']['endTime'] <= val.max) {
                    linkarr[i]["color"] = '#f00';
                } else {
                    linkarr[i]["color"] = '#eee';
                }
            }
            console.log(linkarr);

            graph['links'] = linkarr;

            $('#container2 svg').html('');
            createForce(graph, userMenuData);

            //console.log("起止时间："+stime+" 至 "+etime);
        });

    }

}

createDemos();